import msvcrt
import os
from PyPDF2 import PdfReader, PdfWriter


def delete_last_page(file_path, output_path):
    with open(file_path, 'rb') as file:
        reader = PdfReader(file)
        writer = PdfWriter()

        num_pages = len(reader.pages)
        for i in range(num_pages - 1):
            page = reader.pages[i]
            writer.add_page(page)

        with open(output_path, 'wb') as output_file:
            writer.write(output_file)


def batch_delete_last_page():
    path = os.getcwd()
    out_dir = os.path.join(path, "deleteFile")
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)
    for filename in os.listdir(path):
        if filename.endswith(".pdf"):
            filepath = os.path.join(path, filename)
            output_path = os.path.join(out_dir, filename)
            delete_last_page(filepath, output_path)
            print("删除 %s 最后一页" % filename)


if __name__ == '__main__':
    batch_delete_last_page()
    print("-----已删除完成，请按任意键退出------")
    msvcrt.getch()
